package top.lyc829.iot_android.fragment.index;

import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.model.ApiResult;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xui.widget.actionbar.TitleBar;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import top.lyc829.iot_android.R;
import top.lyc829.iot_android.core.LazyFragment;
import top.lyc829.iot_android.entity.User;
import top.lyc829.iot_android.http.service.UserService;
import top.lyc829.iot_android.http.subscriber.TipProgressLoadingSubscriber;
import top.lyc829.iot_android.mqtt.MqttManager;
import top.lyc829.iot_android.util.LogUtil;
import top.lyc829.iot_android.util.Utils;

import static android.app.Activity.RESULT_OK;
import static com.blankj.utilcode.util.ServiceUtils.bindService;

@Page(name = "IndexFragment")
public class IndexFragment extends LazyFragment {


    @BindView(R.id.btn_door)
    ImageButton btnDoor;

    @BindView(R.id.tv_status)
    TextView tvStatus;

    MqttManager mqttManager = MqttManager.getInstance();

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setTitle("主页")
                .disableLeftView();
        return titleBar;
    }



    public static IndexFragment newInstance() {
        return new IndexFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.index_fragment;
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initListeners() {
//        mqttManager.addSubscribe("/server/openDoorSuccess", mqttMessage -> {
//            //btnDoor.setBackgroundResource(R.drawable.logo);
//            btnDoor.setImageResource(R.drawable.door_open);
//            tvStatus.setText("开");
//        });
//
//        mqttManager.addSubscribe("/server/openDoorFail", mqttMessage -> {
//            btnDoor.setImageResource(R.drawable.door_close);
//            tvStatus.setText("关");
//        });

        mqttManager.addSubscribe("/app/door_status", mqttMessage -> {
            try {
                char tmp = (char) mqttMessage.getPayload()[0];
                if ((int) tmp == 49) {
                    btnDoor.setImageResource(R.drawable.door_open);
                    tvStatus.setText("开");
                } else {
                    btnDoor.setImageResource(R.drawable.door_close);
                    tvStatus.setText("关");
                }
            } catch (Exception e) {
                Utils.SoutMqtte(e);
            }
        });


        btnDoor.setOnClickListener(v -> {
            if (!Utils.isLogin()) {
                Utils.showToast("请先登录");
                return;
            }

            if (tvStatus.getText().toString().equals("关")) {
                // 开门
                XXPermissions.with(this)
                        .permission(Permission.CAMERA)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(List<String> permissions, boolean all) {
                                if (all) {
//                                    XQRCode.setAutoFocusInterval(800);
//                                    XQRCode.startScan(IndexFragment.this, 123);
                                    openDoor("1");
                                }
                            }

                            @Override
                            public void onDenied(List<String> permissions, boolean never) {
                                if (never) {
                                    Utils.showToast("被永久拒绝授权，请手动授予摄像头权限");
                                } else {
                                    Utils.showToast("获取摄像头权限失败");
                                }
                            }
                        });
            } else {
                // 关门
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123 && resultCode == RESULT_OK) {
            //处理扫描结果（在界面上显示）
            handleScanResult(data);
        }
    }

    /**
     * 处理二维码扫描结果
     *
     * @param data
     */
    private void handleScanResult(Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_SUCCESS) {
                    String result = bundle.getString(XQRCode.RESULT_DATA);
                    //Utils.showToast("解析结果:" + result);
                    if (!"123".equals(result)) {
                        Utils.showToast("二维码不正确，请扫描正确的二维码");
                    } else {
                        openDoor(result);
                    }
                } else if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_FAILED) {
                    Utils.showToast("解析二维码失败");
                }
            }
        }
    }

    private void openDoor(String result) {
//        mqttManager.publishMessage("/client/openDoor", result);

        CustomRequest request = XHttp.custom();
        request.call(request.create(UserService.class)
                .openDoor(Integer.parseInt(SPUtils.getInstance().getString("token", "-1"))))
                .subscribeWith(new TipProgressLoadingSubscriber<ApiResult>(getProgressLoader()) {
                    @Override
                    protected void onSuccess(ApiResult apiResult) {
                        if (apiResult.isSuccess()) {
                            Utils.showToast("开门中");
                        } else {
                            Utils.showToast(apiResult.getMsg());
                        }

                    }
                });

    }


    @Override
    public void lazyInit() {

    }
}